import { useState, useCallback, useRef, useEffect } from 'react';
import type { EditorMode, EditorState, FormulaFormatOptions } from '../types';
import { KaTeXRenderer } from '../core/renderer/KaTeXRenderer';
import { insertLatexAtCursor, validateLatex } from '../utils/formulaUtils';

interface UseFormulaEditorOptions {
  initialLatex?: string;
  initialMode?: EditorMode;
  initialFormat?: Partial<FormulaFormatOptions>;
}

/**
 * 公式编辑器Hook - 管理编辑器的核心状态和逻辑
 */
export function useFormulaEditor(options: UseFormulaEditorOptions = {}) {
  const {
    initialLatex = '',
    initialMode = 'visual',
    initialFormat = {}
  } = options;

  // 编辑器状态
  const [state, setState] = useState<EditorState>({
    mode: initialMode,
    latex: initialLatex,
    format: {
      fontSize: 100,
      color: '#000000',
      align: 'center',
      ...initialFormat
    },
    error: undefined
  });

  // 光标位置
  const [cursorPosition, setCursorPosition] = useState(0);
  
  // 防抖定时器引用
  const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // 编辑器引用（用于实时预览）
  const previewRef = useRef<HTMLDivElement>(null);
  const codeEditorRef = useRef<HTMLTextAreaElement>(null);

  /**
   * 更新LaTeX代码
   */
  const updateLatex = useCallback((latex: string, position?: number) => {
    // 验证LaTeX
    const validation = validateLatex(latex);
    
    setState(prev => ({
      ...prev,
      latex,
      error: validation.valid ? undefined : validation.error
    }));

    if (position !== undefined) {
      setCursorPosition(position);
    }
  }, []);

  /**
   * 切换编辑模式
   */
  const toggleMode = useCallback(() => {
    setState(prev => ({
      ...prev,
      mode: prev.mode === 'visual' ? 'code' : 'visual'
    }));
  }, []);

  /**
   * 更新格式选项
   */
  const updateFormat = useCallback((format: Partial<FormulaFormatOptions>) => {
    setState(prev => ({
      ...prev,
      format: {
        ...prev.format,
        ...format
      }
    }));
  }, []);

  /**
   * 插入符号
   */
  const insertSymbol = useCallback((latex: string) => {
    const position = codeEditorRef.current?.selectionStart || cursorPosition;
    const result = insertLatexAtCursor(state.latex, latex, position);
    updateLatex(result.text, result.newCursorPosition);
  }, [state.latex, cursorPosition, updateLatex]);

  /**
   * 处理代码编辑器变化
   */
  const handleCodeChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newLatex = e.target.value;
    const position = e.target.selectionStart;
    updateLatex(newLatex, position);
  }, [updateLatex]);

  /**
   * 处理代码编辑器光标移动
   */
  const handleCursorChange = useCallback((e: React.SyntheticEvent<HTMLTextAreaElement>) => {
    const target = e.target as HTMLTextAreaElement;
    setCursorPosition(target.selectionStart);
  }, []);

  /**
   * 导出编辑器状态
   */
  const exportState = useCallback(() => {
    return {
      latex: state.latex,
      format: state.format,
      mode: state.mode
    };
  }, [state]);

  /**
   * 导入编辑器状态
   */
  const importState = useCallback((importedState: Partial<EditorState>) => {
    setState(prev => ({
      ...prev,
      ...importedState
    }));
  }, []);

  /**
   * 清空编辑器
   */
  const clear = useCallback(() => {
    updateLatex('', 0);
  }, [updateLatex]);

  /**
   * 复制当前LaTeX代码到剪贴板
   */
  const copyLatex = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(state.latex);
      return true;
    } catch (error) {
      console.error('复制失败:', error);
      return false;
    }
  }, [state.latex]);

  /**
   * 从剪贴板粘贴LaTeX代码
   */
  const pasteLatex = useCallback(async () => {
    try {
      const text = await navigator.clipboard.readText();
      const position = codeEditorRef.current?.selectionStart || cursorPosition;
      const result = insertLatexAtCursor(state.latex, text, position);
      updateLatex(result.text, result.newCursorPosition);
      return true;
    } catch (error) {
      console.error('粘贴失败:', error);
      return false;
    }
  }, [state.latex, cursorPosition, updateLatex]);

  /**
   * 实时预览渲染（带防抖）
   */
  useEffect(() => {
    if (!previewRef.current || !state.latex) return;

    // 清除之前的定时器
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    // 设置防抖定时器
    debounceTimerRef.current = setTimeout(() => {
      if (previewRef.current) {
        const { html } = KaTeXRenderer.preview(state.latex, {
          ...state.format,
          displayMode: true,
          throwOnError: false
        });
        previewRef.current.innerHTML = html;
      }
    }, 50); // 50ms防抖

    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
    };
  }, [state.latex, state.format]);

  /**
   * 更新光标位置
   */
  useEffect(() => {
    const textarea = codeEditorRef.current;
    if (textarea && state.mode === 'code') {
      textarea.selectionStart = cursorPosition;
      textarea.selectionEnd = cursorPosition;
    }
  }, [cursorPosition, state.mode]);

  // 返回hook的API
  return {
    state,
    previewRef,
    codeEditorRef,
    updateLatex,
    toggleMode,
    updateFormat,
    insertSymbol,
    handleCodeChange,
    handleCursorChange,
    exportState,
    importState,
    clear,
    copyLatex,
    pasteLatex
  };
}